package the.one.weather.ui.activity;

import android.Manifest;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import com.luck.picture.lib.permissions.RxPermissions;
import com.qmuiteam.qmui.arch.QMUIFragmentActivity;

import org.litepal.tablemanager.Connector;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import the.one.base.base.fragment.BaseFragment;
import the.one.weather.R;
import the.one.weather.ui.fragment.WeatherFragment;
import the.one.weather.util.LitePalUtil;

public class WeatherActivity extends QMUIFragmentActivity {

    private static final String TAG = "WeatherActivity";

    @Override
    protected int getContextViewId() {
        return R.id.main_container;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestPermission(savedInstanceState);
    }

    private void requestPermission(final Bundle savedInstanceState) {
        final RxPermissions permissions = new RxPermissions(this);
        permissions
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_WIFI_STATE)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        // 数据库
                        SQLiteDatabase db = Connector.getDatabase();
                        LitePalUtil.writeCityData(WeatherActivity.this);
                        initFragment(savedInstanceState,new WeatherFragment());
                    }
                });
    }


    private void initFragment(Bundle savedInstanceState, BaseFragment fragment) {
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(getContextViewId(), fragment, fragment.getClass().getSimpleName())
                    .addToBackStack(fragment.getClass().getSimpleName())
                    .commit();
        }
    }

}
